<template>
  <div class="panel-tab__content">
    <el-form size="mini" label-width="100px" @submit.native.prevent :rules="rules" ref="ruleForm"
             :model="elementBaseInfo"
    >
      <el-form-item label="节点key" :prop="idProp">
        <el-input
          v-model="elementBaseInfo.id"
          disabled
          clearable
          @change="updateBaseInfo('id')"
          placeholder="请输入节点key"
          :readonly="this.$route.params.type !== 1 && this.$route.params.type !== '1'"
        />
      </el-form-item>
      <el-form-item label="节点名称" :prop="nameProp">
        <el-input v-model="elementBaseInfo.name" placeholder="请输入节点名称" clearable
                  @change="updateBaseInfo('name')"
                  :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"
        />
      </el-form-item>
    </el-form>
    <el-form size="mini" label-width="100px" @submit.native.prevent :rules="rules" ref="ruleForm"
             :model="propertyForm" prop="name" style="margin-top: 17px"
    >
      <!--流程拓展属性-->
      <el-form-item label="节点描述" :prop="descriptionProp">
        <el-input type="textarea" v-model="propertyForm.description" clearable placeholder="请输入节点描述"
                  @change="saveAttribute('description',propertyForm.description)"
                  :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"
        />
      </el-form-item>
      <el-form-item label="责任单位" :prop="unitProp">
        <el-cascader size="small" :options="deptOptions" clearable :show-all-levels="false"
                     @change="chooseDeptHandle"
                     v-model="propertyForm.unit" filterable style="width: 100%" placeholder="请选择责任单位"
                     :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"
                     :props="{ multiple: true ,emitPath:false}"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="责任岗位">
        <el-select size="small" v-model="propertyForm.post" placeholder="请选择岗位" style="width: 100%;"
                   multiple
                   :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"
                   @change="saveAttribute('post',JSON.stringify(propertyForm.post))" clearable
        >
          <el-option
            size="small"
            v-for="item in postOptions"
            :key="item.postId"
            :label="item.postName"
            :value="item.postId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间要求">
        <el-input v-model="propertyForm.time" clearable
                  @change="saveAttribute('time',propertyForm.time)"
                  placeholder="请输入时间要求"
                  :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"
        />
      </el-form-item>
    </el-form>

    <el-dialog title="主办部门选择" :visible.sync="chooseDeptOpen" append-to-body width="600px">
      <choose-dept @deptValue="deptValue" ref="chooseDept"></choose-dept>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="deptSubmitForm">确 定</el-button>
        <el-button size="small" @click="deptCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { listDept } from '@/api/system/dept'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { businessList } from '@/api/lc/business'
import ChooseDept from '@/plugins/package/tree/chooseDept'
import { deptControlTree2 } from '@/api/system/user'
import { optionselect, getList2 } from '@/api/system/post'

export default {
  name: 'ElementBaseInfo',
  components: { TreeSelect, ChooseDept },
  props: {
    businessObject: Object,
    type: String,
    idEditDisabled: {
      type: Boolean,
      default: true
    }
  },
  inject: {
    prefix: 'prefix',
    width: 'width'
  },
  data() {
    return {
      idProp: '',
      nameProp: '',
      descriptionProp: '',
      unitProp: '',
      chooseDeptOpen: false,
      rules: {
        id: [{ required: true, message: '请输入节点key', trigger: ['blur'] }],
        name: [{ required: true, message: '请输入节点名称', trigger: ['blur'] }],
        description: [{ required: true, message: '请输入节点描述', trigger: ['blur'] }],
        unit: [{ required: true, message: '请输入责任单位', trigger: ['blur', 'change'] }]
      },
      elementBaseInfo: {},
      propertyForm: {
        description: '',
        unit: '',
        post: '',
        time: ''
      },
      editingPropertyIndex: -1,
      bpmnElementPropertyList: [],
      otherExtensionList: [],
      // 部门树选项
      deptOptions: [],
      // 岗位选项
      postOptions: [],
      unitName: '',
      unitId: ''
    }
  },
  watch: {
    businessObject: {
      immediate: false,
      handler: function(val) {
        if (val) {
          this.$nextTick(() => this.resetBaseInfo())
        }
      }
    }
  },
  created() {
    this.getDeptList()
    // this.getPostList()
  },
  methods: {
    getPostList(deptId) {
      if (deptId !== null && deptId !== undefined && deptId !== '') {
        console.log('deptId', deptId)
        getList2(JSON.stringify(deptId)).then(response => {
          this.postOptions = response.data
        })
      }
    },
    resetBaseInfo() {
      const key = document.getElementsByClassName('djs-overlay djs-overlay-context-pad')[0]
      if (key !== undefined && key.length !== 0) {
        key.setAttribute('hidden', true)
      }
      this.bpmnElement = window?.bpmnInstances?.bpmnElement
      this.elementBaseInfo = JSON.parse(JSON.stringify(this.bpmnElement.businessObject))
      console.log('this.elementBaseInfo', this.elementBaseInfo)
      this.bpmnElementProperties =
        this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
          if (ex.$type !== `${this.prefix}:Properties`) {
            this.otherExtensionList.push(ex)
          }
          return ex.$type === `${this.prefix}:Properties`
        }) ?? []
      // 保存所有的 扩展属性字段
      this.bpmnElementPropertyList = this.bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), [])
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []))
      let descriptionValue = ''
      let unitValue = []
      let postValue = []
      let timeValue = ''
      for (let i = 0; i < this.elementPropertyList.length; i++) {
        let key = this.elementPropertyList[i].name
        console.log(key, this.elementPropertyList[i])
        if (key === 'description') {
          descriptionValue = this.elementPropertyList[i].value
        }
        if (key === 'unit') {
          if (this.elementPropertyList[i].value !== '') {
            if (this.elementPropertyList[i].value.includes('[')) {
              unitValue = JSON.parse(this.elementPropertyList[i].value)
            } else {
              unitValue.push(this.elementPropertyList[i].value)
            }
            this.getPostList(unitValue)
          }
        }
        if (key === 'post') {
          if (this.elementPropertyList[i].value !== '') {
            if (this.elementPropertyList[i].value.includes('[')) {
              postValue = JSON.parse(this.elementPropertyList[i].value)
            } else {
              postValue.push(this.elementPropertyList[i].value)
            }
          }
        }
        if (key === 'time') {
          timeValue = this.elementPropertyList[i].value
        }
      }
      this.propertyForm = {
        description: descriptionValue,
        unit: unitValue,
        post: postValue,
        time: timeValue
      }
      console.log('this.elementBaseInfo.$type', this.elementBaseInfo.$type)
      let type = this.elementBaseInfo.$type
      if (type === 'bpmn:UserTask' || type === 'bpmn:StartEvent' || type === 'bpmn:EndEvent') {
        this.idProp = 'id'
        this.nameProp = 'name'
        if (type === 'bpmn:UserTask') {
          this.descriptionProp = 'description'
          this.unitProp = 'unit'
        } else {
          this.descriptionProp = ''
          this.unitProp = ''
        }
      } else {
        this.idProp = ''
        this.nameProp = ''
        this.descriptionProp = ''
        this.unitProp = ''
      }
    },
    updateBaseInfo(key) {
      const attrObj = Object.create(null)
      attrObj[key] = this.elementBaseInfo[key]
      if (key === 'id') {
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
          id: this.elementBaseInfo[key],
          di: { id: `${this.elementBaseInfo[key]}_di` }
        })
      } else {
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, attrObj)
      }
    },
    // 保存拓展字段
    saveAttribute(name, value) {
      console.log('name', name + '111')
      // 判断当前属性是否存在
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []))
      let index = -1
      for (let i = 0; i < this.elementPropertyList.length; i++) {
        let key = this.elementPropertyList[i].name
        if (name === 'description' && key === 'description') {
          index = i
        }
        if (name === 'unit' && key === 'unit') {
          index = i
        }
        if (name === 'post' && key === 'post') {
          index = i
        }
        if (name === 'time' && key === 'time') {
          index = i
        }
      }
      if (index !== -1) {
        window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.bpmnElementPropertyList[index], {
          name,
          value
        })
      } else {
        // 新建属性字段
        const newPropertyObject = window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { name, value })
        // 新建一个属性字段的保存列表
        const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
          values: this.bpmnElementPropertyList.concat([newPropertyObject])
        })
        this.updateElementExtensions(propertiesObject)
      }
    },
    updateElementExtensions(properties) {
      const extensions = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
        values: this.otherExtensionList.concat([properties])
      })
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        extensionElements: extensions
      })
    },
    // 获取部门
    getDeptList() {
      deptControlTree2().then(response => {
        this.deptOptions = response.data
        console.log('this.deptOptions', this.deptOptions)
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    /**
     * 部门弹出
     */
    chooseDeptHandle() {
      this.saveAttribute('unit', JSON.stringify(this.propertyForm.unit))
      this.propertyForm = Object.assign(this.propertyForm, {
        post: ''
      })
      this.saveAttribute('post', this.propertyForm.post)
    },
    /**
     * 部门子页面传参到父页面
     */
    deptValue(data) {
      console.log('部门子页面传参到父页面', data)
      this.unitName = data.label
      this.unitId = data.id
    },
    /**
     * 主办部门选择-确定
     */
    deptSubmitForm() {

    },
    /**
     * 主办部门选择-取消
     */
    deptCancel() {
      this.chooseDeptOpen = false
      this.propertyForm.unit = ''
      this.saveAttribute('unit', JSON.stringify(this.propertyForm.unit))
    },
    businessList() {
      businessList().then(response => {
        this.options = this.handleTree(response.data, 'businessId', 'superiorBusiness')
        console.log('options', this.options)
      })
    }
  },
  beforeDestroy() {
    this.bpmnElement = null
  }
}
</script>
